package com.lxm.leetcode;

/**
 * 动态规划问题
 */
public class DynamicProgramming {

    /**
     * 0,1背包问题
     *
     * @return
     */
    public int package01(int[] val, int[] weight, int maxW) {
        int n = val.length;
        int[][] dp = new int[maxW + 1][n + 1];
        for (int i = 0; i <= maxW; i++) {
            for (int j = 0; j <= n; j++) {
                dp[i][j] = 0;
            }
        }
        for (int i = 1; i <= maxW; i++) {
            for (int j = 1; j <= n; j++) {
                int v = val[j - 1];
                int w = weight[j - 1];
                int la = dp[i][j - 1];
                int cu = dp[Math.max((i - w), 0)][j - 1] + v;
                if (la < cu && w <= i) {
                    dp[i][j] = cu;
                } else {
                    dp[i][j] = la;
                }
            }
        }
        return dp[maxW][n];
    }

    /**
     * 动态规划爬楼梯问题
     *
     * @param n
     * @return
     */
    public int upStairs(int n) {
        int[] dp = new int[8];
        dp[0] = 1;
        dp[1] = 2;
        for (int i = 2; i < n; i++) {
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n - 1];
    }

    /**
     *
     * @param n
     * @return
     */
    public int upStairs1(int n) {
        int l = 2;
        int ll = 1;
        int r = 0;
        for (int i = 3; i <= n; i++) {
            r = l + ll;
            ll = l;
            l = r;
        }
        return r;
    }

    public static void main(String[] args) {
        DynamicProgramming dp = new DynamicProgramming();
        int r = dp.package01(new int[]{3, 4, 5, 6}, new int[]{2, 3, 4, 5}, 8);
        System.out.println(r);
        System.out.println(dp.upStairs(8));
        System.out.println(dp.upStairs1(8));
    }
}
